package com.fenghongzhang.day018;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private PullToRefreshListView pullLv;

    private String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=";
    private int num = 1;
    private MyAdapter myAdapter;

    private List<Food.DataBean> listAll;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //更新ui
            pullLv.onRefreshComplete();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pullLv = (PullToRefreshListView) findViewById(R.id.pullLv);

        listAll = new ArrayList<>();

        myAdapter = new MyAdapter(listAll, MainActivity.this);
        pullLv.setAdapter(myAdapter);
        pullLv.setMode(PullToRefreshBase.Mode.BOTH);

        ILoadingLayout loadingLayoutProxy = pullLv.getLoadingLayoutProxy(true,true);
        loadingLayoutProxy.setRefreshingLabel("正在刷新...");
        loadingLayoutProxy.setReleaseLabel("刷完完成...");
        loadingLayoutProxy.setPullLabel("开始刷新...");

        //下拉刷新
        pullLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//
                handler.sendEmptyMessage(1);

            }

            //上啦加载.
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                num++;
                new MyTask().execute(path+num);
                handler.sendEmptyMessage(1);

            }
        });
        
        //和不同的上下拉模式有关系
//        pullLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
//            @Override
//            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
//                
//            }
//        });


        //拿到原生的listview
        ListView refreshableView = pullLv.getRefreshableView();
        
        refreshableView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "哈哈", Toast.LENGTH_SHORT).show();
            }
        });
        
        refreshableView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "呵呵", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        new MyTask().execute(path+num);
    }


    //2.準備數據源
    class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            URL url = null;
            try {
                url = new URL(strings[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1
                //设置提交方式
//                connection.setRequestMethod("POST");
//                connection.setDoInput(true);
//                connection.setDoOutput(true);
//                OutputStream outputStream = connection.getOutputStream();
//                outputStream.write("stage_id=1&limit=20&page=1".getBytes());
//                outputStream.flush();
//                connection.setReadTimeout(3000);

                //空 GET


                if (connection.getResponseCode() == 200) {
                    InputStream inputStream = connection.getInputStream();
                    StringBuffer buffer = new StringBuffer();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1) {
                        buffer.append(new String(bytes, 0, len));
                    }
                    return buffer.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //Gson
            Gson gson = new Gson();
            Food food = gson.fromJson(s, Food.class);
            //給數據源複製
            //把每次查询都有加入到数据源中.

            List<Food.DataBean> data = food.getData();

            listAll.addAll(data);
            myAdapter.notifyDataSetChanged();

        }
    }
}
